package one.bugu.android.demon.ui.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

/**
 * 滑块可拖动的layout
 */
public class DragFloatActionLayout extends RelativeLayout {

    private static final String TAG = "CustomLayout";

    private Context mContext;

    /**
     * 控件自身的尺寸
     */
    private int mWidth = 0;
    private int mHeight = 0;
    /**
     * 父容器的尺寸
     */
    private int width;
    private int height;
    /**
     * view显示位置
     */
    private int lastX = 0;
    private int lastY = 0;

    /**
     * 是否总是显示在边界
     */
    private boolean alwaysShowBorder = true;

    /**
     * 最长显示动画时长
     */
    public static final long MAX_DURATION = 1000;
    /**
     * 连续点击时间间隔
     */
    public static final long MAX_CLICK = 1000 * 2;


    private OnViewEvent onViewEvent;

    public DragFloatActionLayout(@NonNull Context context) {
        this(context, null);
    }

    public DragFloatActionLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public DragFloatActionLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        this.mContext = context;
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //自己的尺寸
        this.mWidth = w;
        this.mHeight = h;
        //父容器的尺寸
        ViewGroup parent = (ViewGroup) this.getParent();
        width = parent.getWidth();
        height = parent.getHeight();
    }

    float downX = 0;
    float downY = 0;
    float upX = 0;
    float upY = 0;
    long downDuration = 0;
    long upDuration = 0;
    long afTime = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int x = (int) event.getRawX();
        int y = (int) event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //记录按下位置信息及时间
                downX = event.getRawX();
                downY = event.getRawY();
                downDuration = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_MOVE:
                //移动
                transView(x, y);
                break;
            case MotionEvent.ACTION_UP:
                //记录抬起位置信息及时间
                upX = event.getRawX();
                upY = event.getRawY();
                upDuration = System.currentTimeMillis();
                //手机接触view时间超过300毫秒, 此时认为滑动操作
                if (upDuration - downDuration < 300) {
                    //获取view在当前window中的位置
                    int[] location = new int[2];
                    this.getLocationInWindow(location);
                    //判断按下和抬起是否都在当前控件内
                    boolean down_x = downX >= location[0] && downX <= location[0] + mWidth;
                    boolean down_y = downY >= location[1] && downY <= location[1] + mHeight;
                    boolean up_x = upX >= location[0] && upX <= location[0] + mWidth;
                    boolean up_y = upY >= location[1] && upY <= location[1] + mHeight;
                    //如果按下和抬起都在当前控件内,此时为点击事件
                    if (down_x && down_y && up_x && up_y) {
                        //记录点击时间防止重复点击
                        long curTime = System.currentTimeMillis();
                        if (curTime - afTime > MAX_CLICK) {
                            if (onViewEvent != null) {
                                onViewEvent.onViewClick();
                            }
                            //保存该次点击时间
                            afTime = curTime;
                        }
                    }
                } else {
                    if (onViewEvent != null) {
                        onViewEvent.onViewSlip();
                    }
                }
                //移动至边界
                transToBorder(x);
                break;
            case MotionEvent.ACTION_CANCEL:
                //当事件终止时移动至边界
                transToBorder(x);
                break;
        }
        //保存最后位置
        lastX = x;
        lastY = y;
        return true;
    }

    /**
     * 移动
     *
     * @param x 当前移动的X值
     * @param y 当前移动的y值
     */
    private void transView(int x, int y) {
        FrameLayout.MarginLayoutParams layoutParams = (FrameLayout.MarginLayoutParams) getLayoutParams();
        int left = layoutParams.leftMargin + x - lastX;
        int top = layoutParams.topMargin + y - lastY;
        //结界判断
        //左
        left = left < 0 ? 0 : left;
        //上
        top = top < 0 ? 0 : top;
        //右
        left = left > (width - mWidth) ? (width - mWidth) : left;
        //下
        top = top > (height - mHeight) ? (height - mHeight) : top;
        layoutParams.leftMargin = left;
        layoutParams.topMargin = top;
        setLayoutParams(layoutParams);
        requestLayout();
    }

    /**
     * 移动至边界
     *
     * @param left
     */
    private void transToBorder(int left) {
        if (!alwaysShowBorder) {
            return;
        }
        if (left > width / 2) {
            //靠右, 往右移动
            showAnimation(left, width);
        } else {
            //靠左, 往左移动
            showAnimation(left, 0);
        }
    }

    /**
     * 显示动画
     */
    private void showAnimation(int start, int end) {
        Log.d(TAG, "showAnimation: start == " + start + "  end == " + end);
        //根据距离计算动画时长
        if (start == end) {
            return;
        }
        long duration = (Math.abs(end - start) * MAX_DURATION) / (width / 2);
        ValueAnimator animator = ValueAnimator.ofInt(start, end);
        animator.setDuration(duration);
        animator.setInterpolator(new BounceInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int valueX = (int) valueAnimator.getAnimatedValue();
                transView(valueX, lastY);
            }
        });
        animator.start();
    }

    /**
     * 添加布局, 设置初始位置 默认位置在左下角
     */
    public void addContentView(View view) {
        if (view == null) {
            return;
        }
        this.addView(view);
    }

    /**
     * 初始化显示位置
     *
     * @param left
     * @param top
     */
    public void initLocation(int left, int top) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.getLayoutParams();
        layoutParams.leftMargin = left;
        layoutParams.topMargin = top;
        this.setLayoutParams(layoutParams);
    }

    /**
     * 设置点击事件监听
     *
     * @param onViewEvent
     */
    public void setOnViewEvent(OnViewEvent onViewEvent) {
        this.onViewEvent = onViewEvent;
    }

    public interface OnViewEvent {
        /**
         * 点击事件
         */
        void onViewClick();

        /**
         * 滑动事件
         */
        void onViewSlip();
    }
}
